封装的例子 1
[TOC]
main.js 引用
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import Vant from 'vant';
import { Lazyload } from 'vant';
import 'vant/lib/index.css';
import {get, post} from '@/utils/http.js';
import VueClipboard from 'vue-clipboard2'
Vue.config.productionTip = false
Vue.use(Vant);
Vue.use(Lazyload);
Vue.use(VueClipboard)
Vue.prototype.$post = post;
Vue.prototype.$get = get;
new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
src/utils/http.js
import axios from 'axios';
import router from '../router'
import {
  Toast
} from 'vant';
axios.defaults.timeout = 5000;
axios.defaults.baseURL = '';
//http request 拦截器
axios.interceptors.request.use(
  config => {
    if (!config.params.hideLoading) {
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      });
    }
    config.headers = {
      'Content-Type': 'application/json'
    }
    return config;
  },
  error => {
    return Promise.reject(err);
  }
);
//http response 拦截器
axios.interceptors.response.use(
  response => {
    Toast.clear();
    const data = response.data;
    return data;
  },
  error => {
    Toast.clear();
    const status = error.response.status;
    if (status == 401) {
      const current = router.currentRoute.fullPath;
      if (current != '/login') {
        router.push(`/login?redirect=${current}`)
      }
    } else if (status == 500) {
      Toast.fail('服务器异常');
    } else if (status != 200) {
      Toast.fail('请检查请求是否正确');
    }
    return Promise.reject(error)
  }
)
/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
        params: params
      })
      .then(response => {
        resolve(response);
      })
      .catch(err => {
        reject(err)
      })
  })
}
/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response);
      }, err => {
        reject(err)
      })
  })
}
请求的一个例子
<template>
  <div class="detail">
    <template v-if="detail">
      <van-sticky>
        <van-icon name="arrow-left" class="back" @click="back" />
        <video
          :id="detail.data.id"
          controls
          preload="none"
          :poster="detail.data.cover.feed"
          :src="detail.data.playUrl"
        ></video>
      </van-sticky>
      <div class="content">
        <p class="detail-title">{{ detail.data.title }}</p>
        <p class="detail-author-name">
          {{
            detail.data.author != null
              ? detail.data.author.name
              : (detail.data.owner ? detail.data.owner.nickname : '') +
                ' / #' +
                detail.data.category
          }}
        </p>
        <p class="detail-description">{{ detail.data.description }}</p>
        <div class="detail-operation">
          <div class="operation-item">
            <van-icon name="like" />
            <span class="count">{{
              detail.data.consumption.collectionCount
            }}</span>
          </div>
          <div class="operation-item" @click="shareUrl(detail)">
            <van-icon name="share" />
            <span class="count">{{ detail.data.consumption.shareCount }}</span>
          </div>
          <div class="operation-item" @click="download(detail)">
            <van-icon name="down" />
            <span class="count">下载</span>
          </div>
          <div class="operation-item">
            <van-icon name="star" />
            <span class="count">{{
              detail.data.consumption.realCollectionCount
            }}</span>
          </div>
        </div>
      </div>
      <moment :list="relatedList" />
      <moment :list="replies" />
    </template>
  </div>
</template>
<script>
import { getUrl } from '../utils/common.js'
import { Toast } from 'vant'
import moment from '../components/Moment.vue'
export default {
  data() {
    return {
      detail: null,
      relatedList: [],
      replies: [],
    }
  },
  components: {
    moment,
  },
  methods: {
    init() {
      const detail = localStorage.getItem('detail')
      if (detail) {
        this.detail = JSON.parse(detail)
        this.getRelated()
        this.getReplies()
      }
    },
    back() {
      this.$router.push('/')
    },
    shareUrl(content) {
      this.$copyText(content.data.playUrl).then(
        e => {
          Toast.success('已复制')
        },
        e => {
          Toast.fail('复制异常')
        }
      )
    },
    download(content) {
      window.open(content.data.playUrl, '_blank')
    },
    getRelated() {
      this.$get(getUrl('/api/v4/video/related?id=' + this.detail.data.id), {
        hideLoading: true,
      }).then(data => {
        this.relatedList = data.itemList
      })
    },
    getReplies() {
      this.$get(
        getUrl('/api/v2/replies/video?videoId=' + this.detail.data.id),
        { hideLoading: true }
      ).then(data => {
        this.replies = data.itemList
      })
    },
  },
  watch: {
    $route(to, from) {
      this.init()
    },
  },
  mounted() {
    this.init()
  },
}
</script>